package org.dromara.third.auth.util;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.dromara.third.convert.riskObject.dto.RiskObjectDTO;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @Description: AES加密和解密工具类
 * @author admin
 * @Since:2019年9月16日上午11:29:35
 */
public class AESUtil {

    // AES secretKey length (must be 16 bytes)
    @Value("${aes.secret.key}")
    public static String secretKey = "QAZWSXEDCRFVTGBH";

    public static String cityBureauSecretKey = "LYGYJJWWYTSJJKWD";

    // 字符串编码
    private static final String KEY_CHARSET = "UTF-8";

    // 算法方式
    private static final String KEY_ALGORITHM = "AES";

    // 算法/模式/填充
    private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";

    // 私钥大小128/192/256(bits)位 即：16/24/32bytes，暂时使用128，如果扩大需要更换java/jre里面的jar包
    private static final Integer PRIVATE_KEY_SIZE_BIT = 128;

    private static final Integer PRIVATE_KEY_SIZE_BYTE = 16;


    /**
     * @param plainText 明文：要加密的内容
     * @return 密文：加密后的内容，如有异常返回空串：""
     * @Description: 加密
     * @author admin
     * @Since: 2019年9月17日上午10:17:18
     */
    public static String encrypt(String plainText) {
        return encrypt(secretKey, plainText);
    }

    /**
     * @param secretKey 密钥：加密的规则 16位
     * @param plainText 明文：要加密的内容
     * @return cipherText 密文：加密后的内容，如有异常返回空串：""
     * @Description: 加密
     * @author admin
     * @Since: 2019年9月12日下午7:09:31
     */
    public static String encrypt(String secretKey, String plainText) {
        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }

        // 密文字符串
        String cipherText = "";
        try {
            // 加密模式初始化参数
            Cipher cipher = initParam(secretKey, Cipher.ENCRYPT_MODE);
            // 获取加密内容的字节数组
            byte[] bytePlainText = plainText.getBytes(KEY_CHARSET);
            // 执行加密
            byte[] byteCipherText = cipher.doFinal(bytePlainText);
            cipherText = Base64.encodeBase64String(byteCipherText);
        } catch (Exception e) {
            throw new RuntimeException("AESUtil:encrypt fail!", e);
        }
        return cipherText;
    }

    /**
     * @param cipherText 密文：加密后的内容，即需要解密的内容
     * @return 明文：解密后的内容即加密前的内容，如有异常返回空串：""
     * @Description: 解密
     * @author admin
     * @Since: 2019年9月17日上午10:18:19
     */
    public static String decrypt(String cipherText) {
        return decrypt(secretKey, cipherText);
    }


    /**
     * @param cipherText 密文：加密后的内容，即需要解密的内容
     * @return 明文：解密后的内容即加密前的内容，如有异常返回空串：""
     * @Description: 解密
     * @author admin
     * @Since: 2019年9月17日上午10:18:19
     */
    public static String decryptByCityBureau(String cipherText) {
        return decrypt(cityBureauSecretKey, cipherText);
    }


    /**
     * @param secretKey  密钥：加密的规则 16位
     * @param cipherText 密文：加密后的内容，即需要解密的内容
     * @return 编码值
     * @Description: 解密
     * @author admin
     * @Since: 2019年9月12日下午7:10:06
     */
    public static String decrypt(String secretKey, String cipherText) {

        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }

        // 明文字符串
        String plainText = "";
        try {
            Cipher cipher = initParam(secretKey, Cipher.DECRYPT_MODE);
            // 将加密并编码后的内容解码成字节数组
            byte[] byteCipherText = Base64.decodeBase64(cipherText);
            // 解密
            byte[] bytePlainText = cipher.doFinal(byteCipherText);
            plainText = new String(bytePlainText, KEY_CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("AESUtil:decrypt fail!", e);
        }
        return plainText;
    }

    /**
     * 初始化参数
     *
     * @param secretKey 密钥：加密的规则 16位
     * @param mode      加密模式：加密or解密
     */
    public static Cipher initParam(String secretKey, int mode) {
        try {
            // 防止Linux下生成随机key
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secretKey.getBytes());
            // 获取key生成器
            KeyGenerator keygen = KeyGenerator.getInstance(KEY_ALGORITHM);
            keygen.init(PRIVATE_KEY_SIZE_BIT, secureRandom);

            // 获得原始对称密钥的字节数组
            byte[] raw = secretKey.getBytes();

            // 根据字节数组生成AES内部密钥
            SecretKeySpec key = new SecretKeySpec(raw, KEY_ALGORITHM);
            // 根据指定算法"AES/CBC/PKCS5Padding"实例化密码器
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
            IvParameterSpec iv = new IvParameterSpec(secretKey.getBytes());

            // 初始化AES密码器
            cipher.init(mode, key, iv);

            return cipher;
        } catch (Exception e) {
            throw new RuntimeException("AESUtil:initParam fail!", e);
        }
    }

    /**
     * 获取ip
     * @param request
     * @return
     */
    public static String getIPAddress(HttpServletRequest request) {
        String ip = null;

        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String test1() {
        RiskObjectDTO riskObjectDTO = new RiskObjectDTO();
        riskObjectDTO.setId(196849474779860582L);
        riskObjectDTO.setRiskObjectCode("123456");
        riskObjectDTO.setAnalysisName("分析名称");
        riskObjectDTO.setRiskObjectType("1");
        riskObjectDTO.setIsDanger("0");
        riskObjectDTO.setHazardDept("100");
        riskObjectDTO.setHazardLiablePerson("测试");
        riskObjectDTO.setAreaSite("1");
        riskObjectDTO.setDelFlag("0");
        riskObjectDTO.setCreateDept("100");
        riskObjectDTO.setCreateBy("1");
        riskObjectDTO.setCreateTime("2025-09-18 16:22:20");
        riskObjectDTO.setUpdateBy("1");
        riskObjectDTO.setUpdateTime("2025-09-18 16:22:20");
        return JSONObject.toJSONString(riskObjectDTO);
    }

    public static void main(String[] args) {
        String s = test1();
        String encrypt = encrypt(s);
        System.out.println(encrypt);
    }
}


